package com.shuqi.activity.viewport;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;

import com.shuqi.activity.BookSearchParentActivity;
import com.shuqi.activity.BookSearchResultActivity;
import com.shuqi.activity.adapter.SearchPopupWindowAdapter;
import com.shuqi.common.utils.Log4an;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.SearchHistoryDao;
import com.shuqi.model.bean.SearchAssociateInfo;

/**
 * 搜索联想和搜索历史弹出框
 * 
 * @author linyuren
 * 
 */
public class SearchPopupWindow implements OnClickListener, OnDismissListener {

    private PopupWindow mPop;
    private Activity activity;
    private View pwView;
    private ListView lv;
    private SearchPopupWindowAdapter adapter;

    /** 搜索联想数据源 */
    private List<SearchAssociateInfo> onLineList = null;
    /** 历史记录数据源 */
    private List<SearchAssociateInfo> localList;
    /** 最后一次连网的搜索内容 */
    private String searchContentOld = null;
    /** 防止editText为空替换数据 */
    private String isSearchContentNull = null;
    /** 是否正在连网 false=正在连网 */
    private boolean isEnd = true;
    /** 关闭历史记录 */
    private boolean isCloseLocal = false;

    /** 初始化 */
    public SearchPopupWindow(Activity activity) {
        this.activity = activity;
        this.pwView = LayoutInflater.from(activity).inflate(R.layout.item_search_popupwindow, null);
        this.mPop =
                new PopupWindow(pwView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, false);
        this.mPop.setOnDismissListener(this); // 实现监听pop销毁事件
        this.mPop.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        this.mPop.setBackgroundDrawable(new ColorDrawable());
        this.mPop.setOutsideTouchable(true);
        this.lv = (ListView) this.pwView.findViewById(R.id.search_pw_lv);
        this.pwView.findViewById(R.id.search_pw_clear).setOnClickListener(this);
    }

    /** 判断显示状态 */
    public void showJudgePW(Activity activity, final String searchContent, View view,
            List<SearchAssociateInfo> onlineList) {
        isSearchContentNull = searchContent;
        if (TextUtils.isEmpty(searchContent)) {// 本地
            /** 读取数据库数据 */
            List<String> loclal = SearchHistoryDao.getInstance().getSearchHistoryList();
            Log4an.e("mine", "传递过来的搜索词：" + searchContent + ";历史记录：" + loclal.toString());
            this.localList = new ArrayList<SearchAssociateInfo>();
            for (int i = 0; i < loclal.size(); i++) {
                String histroyTitle = loclal.get(i);
                SearchAssociateInfo tempInfo = new SearchAssociateInfo();
                tempInfo.setHistroyInfo(histroyTitle);
                this.localList.add(tempInfo);
            }
            if (localList != null && localList.size() > 0) {
                this.pwView.findViewById(R.id.search_pw_clear).setOnClickListener(this);
                this.pwView.findViewById(R.id.search_pw_ll2).setVisibility(View.VISIBLE);
                this.adapter = new SearchPopupWindowAdapter(activity, localList, false);
                this.lv.setAdapter(adapter);
                // 因产品需求许手动修改listview的高度
                int totalHeight = 0;
                for (int i = 0; i < adapter.getCount() && i < 4; i++) {
                    View listItem = adapter.getView(i, null, lv);
                    listItem.measure(0, 0);
                    totalHeight += listItem.getMeasuredHeight();
                }
                ViewGroup.LayoutParams params = lv.getLayoutParams();
                params.height = totalHeight + (lv.getDividerHeight() * (adapter.getCount() - 1));
                lv.setLayoutParams(params);

                this.showPW(view);
            } else {
                this.closePW();
            }
        } else {// 联想
            this.getOnLineData(searchContent, view, onlineList);
        }
    }

    /** 联想功能 */
    public void getOnLineData(final String searchContent, final View view,
            final List<SearchAssociateInfo> onlineList) {
        if (!isEnd) {// 如果正在连网return
            return;
        } else if (!TextUtils.isEmpty(searchContentOld) && searchContentOld.equals(searchContent)) {// 如果当前editView上字符串与最后一次连网的字符串相同，直接显示，不连网
            showOnLineList(view);
            return;
        }
        searchContentOld = searchContent;
        new Thread(new Runnable() {
            @Override
            public void run() {
                isEnd = false;
                onLineList = onlineList;
                isEnd = true;
                if (!searchContentOld.equals(searchContent)) {// 如果最后一次联想与当前字符串不同，从新联想当前字符串
                    getOnLineData(searchContent, view, onlineList);
                } else {
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            showOnLineList(view);
                        }
                    };
                    activity.runOnUiThread(runnable);
                }
            }
        }).start();
    }

    /** 适配联想数据 */
    private void showOnLineList(final View view) {
        if (onLineList != null && onLineList.size() > 0 && !TextUtils.isEmpty(isSearchContentNull)) {
            adapter = new SearchPopupWindowAdapter(activity, onLineList, true);
            lv.setAdapter(adapter);

            // 因产品需求许手动修改listview的高度
            int totalHeight = 0;
            for (int i = 0; i < adapter.getCount() && i < 5; i++) {
                View listItem = adapter.getView(i, null, lv);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
            ViewGroup.LayoutParams params = lv.getLayoutParams();
            params.height = totalHeight + (lv.getDividerHeight() * (adapter.getCount() - 1));
            lv.setLayoutParams(params);

            if (pwView.findViewById(R.id.search_pw_ll2).getVisibility() == View.VISIBLE) {
                pwView.findViewById(R.id.search_pw_ll2).setVisibility(View.GONE);
            }
            showPW(view);
        } else {
            closePW();
        }
    }

    /** 弹出显示框 */
    public void showPW(View view) {
        if (activity != null && mPop != null && !mPop.isShowing() && view.isShown()) {
            try {
                mPop.setWidth(view.getWidth());
                mPop.showAsDropDown(view, 0, 0);
                if (activity instanceof BookSearchParentActivity) {
                    ((BookSearchParentActivity) activity).mShowSearchBackGround(true);
                } else {
                    ((BookSearchResultActivity) activity).mShowSearchBackGround(true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /** 关闭弹出框 */
    public void closePW() {
        if (mPop != null && mPop.isShowing()) {
            try {
                mPop.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /** 返回弹出框显示状态 */
    public boolean isShowPW() {
        return mPop.isShowing();
    }

    /** 判断是否是本地 */
    public boolean isCloseLocal() {
        return isCloseLocal;
    }

    public void setCloseLocal(boolean isClose) {
        this.isCloseLocal = isClose;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_pw_clear:
                SearchHistoryDao.getInstance().clearAllSearchHistory();
                closePW();
                break;
        }
    }

    @Override
    public void onDismiss() {
        if (activity != null && mPop != null && !mPop.isShowing()) {
            if (activity instanceof BookSearchParentActivity) {
                ((BookSearchParentActivity) activity).mShowSearchBackGround(false);
            } else {
                ((BookSearchResultActivity) activity).mShowSearchBackGround(false);
            }
        }
    }

}
